//
//  ViewController.m
//  3DTransformDemo
//
//  Created by Ju on 15/6/3.
//  Copyright (c) 2015年 juwenz. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIView *left;
@property (weak, nonatomic) IBOutlet UIView *right;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupGesture];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupBackgroundImage];
}

- (void)setupGesture
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(open:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:tap];
}

- (void)setupBackgroundImage
{
    UIImage *image = [UIImage imageNamed:@"background.jpg"];
    
    self.view.layer.contents = (__bridge id)(image.CGImage);
    self.view.layer.contentsGravity = kCAGravityResizeAspectFill;
    
    self.left.layer.contents = (__bridge id)(image.CGImage);
    self.left.layer.contentsGravity = kCAGravityResizeAspect;
    self.left.layer.contentsScale = [UIScreen mainScreen].scale;
    self.left.layer.contentsRect = CGRectMake(0, 0, 0.5, 1);
    
    self.right.layer.contents = (__bridge id)(image.CGImage);
    self.right.layer.contentsGravity = kCAGravityResizeAspect;
    self.right.layer.contentsScale = [UIScreen mainScreen].scale;
    self.right.layer.contentsRect = CGRectMake(0.5, 0, 0.5, 1);
    
}

- (IBAction)open:(id)sender {
    CATransform3D perspective =  CATransform3DIdentity;
    
    perspective.m34 = -1/500;
    
    self.view.layer.sublayerTransform = perspective;
    //改变左边视图旋转轴心
    self.left.layer.anchorPoint = CGPointMake(0, 0.5);
    CGPoint center = self.left.center;
    center.x = 0;
    self.left.layer.position = center;
    
    //改变右边视图轴心
    self.right.layer.anchorPoint = CGPointMake(1, 0.5);
    center = CGPointMake(CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)/2);
    self.right.layer.position = center;
    
    [UIView animateWithDuration:1 animations:^{
        CATransform3D tranform1 = CATransform3DMakeRotation(-M_PI_2, 0, 1, 0);
        self.left.layer.transform = tranform1;
        
        CATransform3D tranform2 = CATransform3DMakeRotation(M_PI_2, 0, 1, 0);
        self.right.layer.transform = tranform2;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1 animations:^{
            self.left.layer.transform = CATransform3DIdentity;
            self.right.layer.transform = CATransform3DIdentity;
        }];
    }];
    
    
}


@end
